﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Threading;

namespace CallStudent
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 待点名单列表集合
        /// </summary>
        private List<String> DaiDianList = new List<string>();

        /// <summary>
        /// 已点名单列表集合
        /// </summary>
        private List<String> YiDianList = new List<string>();

        /// <summary>
        /// 特定名单：【key：第几次点名序号】
        /// </summary>
        private Dictionary<int,string> TeDingMingDan = new Dictionary<int,String>();

        /// <summary>
        /// 点名次数序号
        /// </summary>
        private int DianMingIndex = 0;

        /// <summary>
        /// 点名倒计时已计数时间（秒）
        /// </summary>
        int count_time = 0;

        /// <summary>
        /// 点名倒计时总时间（秒）
        /// </summary>
        int totail_time = 3;

        /// <summary>
        /// 是否抽取名单
        /// </summary>
        bool isChuQu = false;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                string fileName = "名单.txt";
                Encoding encoding = GetTextFileEncodingType(fileName);
                //读取名单文件
                using (StreamReader ReaderObject = new StreamReader(fileName, encoding))
                {
                    string Line;
                    // ReaderObject reads a single line, stores it in Line string variable and then displays it on console
                    while ((Line = ReaderObject.ReadLine()) != null)
                    {
                        if (Line.IndexOf("-") != -1)
                        {
                            // 通过 - 检测名单中是否存在特定名单，目前特定名单只支持第X次点名时点中
                            string[] str = Line.Split('-');
                            
                            //中奖轮次
                            int zhongJiangLunCi = 0;
                            if (int.TryParse(str[1], out zhongJiangLunCi))
                            {
                                TeDingMingDan.Add(zhongJiangLunCi, str[0]);
                            }
                            Line = str[0];
                        }
                        DaiDianList.Add(Line);
                    }
                }

            }
            catch (Exception ex)
            {
                // 读取名单文件异常，文件不存在

                this.LabDianMing.Text = "请设置名单";
                this.BtnBegin.Enabled = false;
                this.LabDaiDian.Text = "0";
                this.LabYiDian.Text = "0";
            }
            
            if (DaiDianList == null || DaiDianList.Count <= 0)
            {
                this.LabDianMing.Text = "请设置名单";
                this.BtnBegin.Enabled = false;
                this.LabDaiDian.Text = "0";
                this.LabYiDian.Text = "0";
            }
            else 
            {
                this.LabDaiDian.Text = DaiDianList.Count.ToString();
                this.LabYiDian.Text = YiDianList.Count.ToString();
            }
        }

        private void BtnBegin_Click(object sender, EventArgs e)
        {
            if (DaiDianList == null || DaiDianList.Count <= 0) 
            {
                MessageBox.Show("您已点完所有名单，要继续点名请退出后重新开始");
                return;
            }

            // 开始点名，增加已点名轮次
            DianMingIndex ++;
            this.BtnBegin.Enabled = false;
            this.BtnBegin.Text = this.totail_time.ToString();
            timer1.Interval = 1000;
            timer1.Enabled = true;
            
            isChuQu = true;

            this.backgroundWorker1.RunWorkerAsync();

            timer1.Start();
        }

        /// <summary>
        /// 计数器进行点名计算倒计时处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            count_time++;
            this.BtnBegin.Text = (this.totail_time - this.count_time).ToString();
            if(count_time == totail_time) 
            {
                timer1.Stop();
                isChuQu = false;
                count_time = 0;
                this.BtnBegin.Text = "开始";
                this.BtnBegin.Enabled = true;
            }
        }


        /// <summary>
        /// 倒计时过程中跳动计算中的名单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string dianMing = "";
            int dianMingIndex = 0;
            while (isChuQu)
            {

                Random rm = new Random();

                dianMingIndex = rm.Next(DaiDianList.Count);

                dianMing = DaiDianList[dianMingIndex];

                backgroundWorker1.ReportProgress(50,dianMing);

                Thread.Sleep(10);
            }
            
            if (TeDingMingDan.ContainsKey(DianMingIndex)) 
            {
                dianMing = TeDingMingDan[DianMingIndex];
                backgroundWorker1.ReportProgress(100, dianMing);
            }

            YiDianList.Add(dianMing);
            DaiDianList.Remove(dianMing);

            
        }


        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.LabDianMing.Text = e.UserState.ToString();

            this.LabDaiDian.Text = DaiDianList.Count.ToString();
            this.LabYiDian.Text = YiDianList.Count.ToString();
        }


        /// <summary>
        /// 获取文本文件的字符编码类型
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        static Encoding GetTextFileEncodingType(string fileName) 
        {
            Encoding encoding = Encoding.Default;
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            BinaryReader binaryReader = new BinaryReader(fileStream, encoding);
            byte[] buffer = binaryReader.ReadBytes((int)fileStream.Length);
            binaryReader.Close();
            fileStream.Close();
            if (buffer.Length >= 3 && buffer[0] == 239 && buffer[1] == 187 && buffer[2] == 191)
            {
                encoding = Encoding.UTF8;
            }
            else if (buffer.Length >= 3 && buffer[0] == 254 && buffer[1] == 255 && buffer[2] == 0)
            {
                encoding = Encoding.BigEndianUnicode;
            }
            else if (buffer.Length >= 3 && buffer[0] == 255 && buffer[1] == 254 && buffer[2] == 65)
            {
                encoding = Encoding.Unicode;
            }
            else if (IsUTF8Bytes(buffer)) 
            {
                encoding = Encoding.UTF8;
            }
            return encoding;
        }
 
        /// <summary>
        /// 判断是否是不带 BOM 的 UTF8 格式
        /// BOM（Byte Order Mark），字节顺序标记，出现在文本文件头部，Unicode编码标准中用于标识文件是采用哪种格式的编码。
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 
            byte curByte; //当前分析的字节. 
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前 
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1 
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式");
            }
            return true;
        }
    }
}
